// 防抖
export function _debounce(fn, delay) {
  var delay = delay || 200;
  let timer;
  return function () {
    const th = this;
    const args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function () {
      timer = null;
      fn.apply(th, args);
    }, delay);
  };
}

// 节流
export function _throttle(fn, interval) {
  var last;
  var timer;
  var interval = interval || 2000;
  return function () {
    var th = this;
    var args = arguments;
    var now = +new Date();
    if (last && now - last < interval) {
      clearTimeout(timer);
      timer = setTimeout(function () {
        last = now;
        // fn.apply(th, args);
      }, interval);
    } else {
      last = now;
      fn.apply(th, args);
    }
  };
}

// 获取当前时间到30天之后的日期区间
export function getTimeWeek() {
  var startDate = new Date();
  var endDate = new Date();
  endDate.setDate(startDate.getDate() + 30);
  var dataArr = [];
  var weeks = ["日", "一", "二", "三", "四", "五", "六"];
  var weekDays = ["1", "2", "3", "4", "5", "6", "7"];
  while (endDate.getTime() - startDate.getTime() >= 0) {
    var month = (startDate.getMonth() + 1).toString().length == 1 ? "0" + (startDate.getMonth() + 1).toString() : startDate.getMonth() + 1;
    var day = startDate.getDate().toString().length == 1 ? "0" + startDate.getDate() : startDate.getDate();
    var week = weeks[startDate.getDay()];
    dataArr.push({
      day: month + "-" + day,
      week: "周" + week,
      weekDay: weekDays[startDate.getDay()],
    });
    startDate.setDate(startDate.getDate() + 1);
  }
  dataArr[0].week = "今天";
  dataArr[1].week = "明天";
  dataArr[2].week = "后天";
  return dataArr;
}

// 判断用户每天是否第一次打开此页面
export function isFirstOpenPage() {
  // 获取当前日期，并转换成字符串形式
  const today = new Date();
  const todayStr = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`;
  // 判断localStorage中是否已经存储了当前日期，如果没有则存储
  const lastDate = uni.getStorageSync("lastDate");
  if (lastDate !== todayStr) {
    uni.setStorageSync("lastDate", todayStr);
    // 在这里执行用户每天第一次打开此页面的相关逻辑
    return true;
  }
  return false;
}

// 秒 转化为 时 分 秒
export function getTime(time, type) {
  // 转换为式分秒
  let h = parseInt((time / 60 / 60) % 24);
  h = h < 10 ? "0" + h : h;
  let m = parseInt((time / 60) % 60);
  m = m < 10 ? "0" + m : m;
  let s = parseInt(time % 60);
  s = s < 10 ? "0" + s : s;
  // 作为返回值返回
  if (type === "time") {
    return `${h}:${m}:${s}`;
  } else {
    return [h, m, s];
  }
}

// 数字 1 2 3 4 5 6 ...  转化为 一 二 三 四 五 六 ...
export function rp(n) {
  const cnum = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"];
  var s = "";
  n = "" + n; // 数字转为字符串
  for (var i = 0; i < n.length; i++) {
    s += cnum[parseInt(n.charAt(i))];
  }
  if (s.length == 2) {
    // 两位数的时候
    // 如果个位数是0的时候，令改成十
    if (s.charAt(1) == cnum[0]) {
      s = s.charAt(0) + cnum[10];
      // 如果是一十改成十
      if (s == cnum[1] + cnum[10]) {
        s = cnum[10];
      }
    } else if (s.charAt(0) == cnum[1]) {
      // 如果十位数是一的话改成十
      s = cnum[10] + s.charAt(1);
    }
  }
  return s;
}

/**
 * 时间格式转换
 */
export function formatDate(date, format = "YYYY年MM月DD日") {
  date = new Date(Date.parse(date));
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const monthStr = month < 10 ? `0${month}` : `${month}`;
  const dayStr = day < 10 ? `0${day}` : `${day}`;
  const formatStr = format.replace("YYYY", year).replace("MM", monthStr).replace("DD", dayStr);
  return formatStr;
}

// 获取两个时间之差 与当前之前做对比
export function differTime(dateString, type) {
  // 将传入的时间字符串转为Date对象
  var d1 = new Date(dateString);
  var d2 = new Date();
  var timeDiff = {};
  var diff = (d2.getTime() - d1.getTime()) / 1000;
  if (diff < 0) {
    if (type === "time") {
      timeDiff.day = Math.floor(-diff / (24 * 60 * 60));
      diff += timeDiff.day * 24 * 60 * 60;
    }
    timeDiff.hours = Math.floor(-diff / 3600);
    diff += timeDiff.hours * 3600;
    timeDiff.minutes = Math.floor(-diff / 60);
    diff += timeDiff.minutes * 60;
    timeDiff.seconds = Math.floor(-diff);
  } else {
    timeDiff.day = 0;
    timeDiff.hours = 0;
    timeDiff.minutes = 0;
    timeDiff.seconds = 0;
  }
  if (type === "time") {
    return `${timeDiff.day}天${timeDiff.hours}小时${timeDiff.minutes}分${timeDiff.seconds}秒`;
  } else {
    return timeDiff;
  }
}
// rpx 转 px  用于video 视频高度  原因：打包ios App端 如果高度不是px 并且有小数点的话 controls会不显示 存在bug https://ask.dcloud.net.cn/question/163720
export function rpxToPx(rpx) {
  const screenWidth = uni.getSystemInfoSync().screenWidth;
  return parseInt((screenWidth * Number.parseInt(rpx)) / 750) + "px";
}

// 设置rich-text 里面的 img 宽度100%
export function editRichTextCss(htmlString) {
	// let newContent = content.replace(/\/\>/gi, ' style="max-width:100%;height:auto;width:100%;"/>');
	// return newContent;
	// 使用正则表达式匹配所有 <img> 标签
	  const regex = /<img([^>]*)>/gi;
	  
	  // 替换匹配到的 <img> 标签，添加 style 属性
	  const modifiedHtml = htmlString.replace(regex, (match, p1) => {
	    // 检查是否已有 style 属性
	    if (p1.includes('style=')) {
	      // 如果已有 style 属性，追加 width: 100%（避免重复）
	      const styleRegex = /(style="[^"]*)/gi;
	      return match.replace(styleRegex, `$1; max-width:100%;height:auto;width:100%;display:block;"`);
	    } else {
	      // 如果没有 style 属性，直接添加
	      return `<img${p1} style="max-width:100%;height:auto;width:100%;display:block;">`;
	    }
	  });
	  
	  return modifiedHtml;	  
}